import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { parseLyric } from '../../utils/tool';
import DragContainer from '../../common/drag_container';
import './index.scss';

interface LyricProps {
  isShow: boolean;
  lyric: string;
  currentTime: number;
  themeColor?: string;
  close: () => void;
}

const Lyric: React.FC<LyricProps> = (props: LyricProps) => {
  const { isShow = false, lyric = '', currentTime = 0, themeColor = '', close } = props;

  const [lyricIndex, setLyricIndex] = useState(0);
  const lyricArr = useMemo(() => parseLyric(lyric), [lyric]);

  useEffect(() => {
    if (!lyricArr.length) {
      return;
    }
    const _currentTime = currentTime / 1000;
    for (let i = 0, { length } = lyricArr; i < length; i++) {
      const line = lyricArr[i];
      const nextLine = lyricArr[i + 1];
      if (line && line?.length && nextLine && nextLine?.length) {
        /** 如果歌曲currentTime大于当前行歌曲时间，并且，下一行不为空或者当前currentTime小于下一行时间 */
        if (_currentTime >= line?.[0] && (_currentTime < nextLine[0] || !nextLine)) {
          setLyricIndex(i);
        }
      }
    }
  }, [lyricArr, lyricIndex, currentTime]);

  const lyricContentStyle = useMemo(
    () => ({
      transform: `translateY(${-lyricIndex * 30}px)`,
      color: themeColor
    }),
    [lyricIndex]
  );

  return (
    <DragContainer isShow={isShow} position="bottomCenter" copyStyle={{ borderRadius: '8px' }}>
      <div className="fplayer_lyric">
        <span className="iconfont fplayer-close" onClick={close} />
        <div className="fplayer_lyric_content">
          {lyricArr?.length ? (
            <ul style={lyricContentStyle}>
              {lyricArr.map((item, i) => (
                <li key={i}>{item?.[1] ? item[1] : '暂无歌词'}</li>
              ))}
            </ul>
          ) : (
            '暂无歌词'
          )}
        </div>
      </div>
    </DragContainer>
  );
};

export default Lyric;
